import { remove } from 'lodash'
import { defineStore } from 'pinia'
/* import interlocutionApi from '@/api/interlocution' */
import { ElMessage } from 'element-plus'
const selectType = [
  {
    value: 'history',
    label: '历史对话'
  },
  {
    value: 'quick',
    label: '快速问答'
  }
]

const getQuestionList = async (type) => {
  return [] /* new Promise(async (resolve) => {
    let [err, res] = await interlocutionApi.getQuestionList(type)
    let retData = []
    if (err) {
      console.error(`fetch dict failed, err: ${err}`)
    } else if (res.data && Array.isArray(res.data.data)) {
      retData = res.data.data
    } else {
      console.error(`fetch dict failed, cannot find data`)
    }
    resolve({ data: retData })
  }) */
}
const historyData = [{
  title:'新对话窗口',

}]
export const useDialogue = defineStore('dialogue', {
  state: () => ({
    type: selectType[0], // 问题列表类别
    helperList: [],
    helperListLoading: false,
    isShowHome: true,
    askList: [], // 快速问答
    historyList: historyData, // 历史对话列表
    historyLoading: false,
    addHistoryLoading: false,
    activeHistory: {}, // 激活的历史对话
    showPdf: false, // 显示历史对话
    pdfUrl: '',
    pdfPageNum: 0,
    // 对话问答列表
    dialogueList: [],
    isSending: false, // 是否正在发送信息，正在发送信息时，不能进行其他操作
    excelBatchSearchLoading: false //批量查询正在进行中，不能进行其他操作
  }),
  actions: {
    async getHelperList() {
      this.helperListLoading = true
      let [err, res] = await interlocutionApi.getHelperList()
      this.helperListLoading = false
      if (err) {
        ElMessage.error('获取助手中心数据失败')
        return
      }
      this.helperList = res.data.data
    },
    updateType(type) {
      this.type = type
    },
    isHistory() {
      return this.type.value === selectType[0].value
    },
    updateisShowHome(isShow) {
      if (!this.isSendingVaild()) {
        return
      }
      this.isShowHome = isShow
      if (isShow) {
        this.activeHistory = {}
        this.updateShowPdf(false)
      }
    },
    //#region 问题列表相关
    async getQuestionList(typeId) {
      if (typeId) {
        const res = await getQuestionList(typeId)
        this.askList = res.data
      }
    },
    async deleteQuestionItem(item) {
      let [err, res] = await interlocutionApi.deleteQuestionItem(item.id)
      if (err) {
        ElMessage.error('删除失败')
        return
      }
      ElMessage.success('删除成功')
      this.askList = remove(this.askList, (askItem) => {
        return askItem.id !== item.id
      })
    },
    async addNewQuestion(params) {
      let [err, res] = await interlocutionApi.postAddQuestion(params)
      if (err) {
        ElMessage.error('添加失败')
        return
      }
      ElMessage.success('添加成功')
      this.getQuestionList(this.activeHistory.typeCode)
    },
    //#endregion
    //#region 历史对话
    async getHistoryList() {
      this.historyLoading = true
      let [err, res] = await interlocutionApi.getHistroyDialogueList()
      this.historyLoading = false
      if (err) {
        ElMessage.error('获取历史对话失败')

        return
      }
      this.historyList = res.data.data
    },
    // 获取新添加的问答记录，并将其添加到历史问答列表中andAsk
    /** 如果是新增历史记录， */
    async addHistoryItem(item, andAsk = false) {
      this.addHistoryLoading = true
      let [err, res] = await interlocutionApi.postCreateHistroyDialogue(item)
      this.addHistoryLoading = false
      if (err) {
        ElMessage.error('新建失败')
        return
      }
      ElMessage.success('新建成功')
      this.updateType(selectType[0])
      this.updateActiveHistory(res.data.data, false)
      this.dialogueList = []
      this.historyList.unshift(res.data.data)
      /* if (andAsk) {
        bus.emit('sendMessage', item.title)
      } */
    },
    // 如果是新增的历史记录则无需获取历史对话getDialogue
    updateActiveHistory(item, getDialogue = true) {
      if (!this.isSendingVaild()) {
        return
      }
      this.updateisShowHome(false)
      this.updateShowPdf(false)
      this.activeHistory = item
      this.getQuestionList(item.typeCode)

      // 切换历史记录，则获取历史记录中的历史聊天记录
      if (getDialogue) {
        this.getDialogueList(item.historyId)
      }
    },
    async updateHistoryItem(item) {
      const { historyId, title } = item
      let [err, res] = await interlocutionApi.postHistroyEditDialogue({ historyId, title })
      if (err) {
        ElMessage.error('修改失败')
        return
      }
      ElMessage.success('修改成功')

      this.historyList = this.historyList.map((select) => {
        if (select.historyId === item.historyId) {
          return {
            ...item
          }
        }
        return select
      })
    },
    async deleteHistoryItem(item) {
      if (item.historyId === this.activeHistory.historyId) {
        this.updateisShowHome(true)
      }
      let [err, res] = await interlocutionApi.deleteHistroyDialogue(item.historyId)
      if (err) {
        ElMessage.error('删除失败')
        return
      }
      ElMessage.success('删除成功')
      this.historyList = remove(this.historyList, (select) => {
        return select.historyId !== item.historyId
      })
    },
    async clearHistoryList() {
      let [err, res] = await interlocutionApi.deleteHistroyDialogueAll(0)
      if (err) {
        ElMessage.error('清空失败')
        return
      }
      ElMessage.success('数据清空')
      this.updateisShowHome(true)
      this.historyList = []
    },
    //#endregion
    //#region 问答对话相关
    // 获取某历史记录的对话列表
    async getDialogueList(val) {
      let [err, res] = await interlocutionApi.getDialogueList(val)
      if (err) {
        ElMessage.error('获取的问答列表数据失败')
        return
      }
      this.dialogueList = res.data.data.map((item) => {
        return {
          ...item,
          answer: { ...item.answer, visible: false }
        }
      })
    },
    isSendingVaild() {
      if (this.isSending || this.excelBatchSearchLoading) {
        ElMessage.warning('对话还没有结束，请稍后再试！')
        return false
      }
      return true
    },
    //#endregion

    updateShowPdf(show) {
      this.showPdf = show
    },
    updatePdfUrl(url) {
      this.pdfUrl = url
    },
    updatePageNum(pageNum) {
      this.pdfPageNum = pageNum
    },
    // 如果为批量查询才会显示上传excel查询
    showImportExcel() {
      return this.activeHistory.typeCode === 7 // 批量查询才会显示上传excel查询
    }
  }
})
